home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / perl5 / RPC / XML / Server.pm < prev    next >
Encoding:
Perl POD Document  |  2008-09-15  |  76.3 KB  |  2,115 lines

  1. ###############################################################################
  2. #
  3. # This file copyright (c) 2001-2008 Randy J. Ray, all rights reserved
  4. #
  5. # See "LICENSE" in the documentation for licensing and redistribution terms.
  6. #
  7. ###############################################################################
  8. #
  9. #   $Id: Server.pm 343 2008-04-09 09:54:36Z rjray $
  10. #
  11. #   Description:    This class implements an RPC::XML server, using the core
  12. #                   XML::RPC transaction code. The server may be created with
  13. #                   or without an HTTP::Daemon object instance to answer the
  14. #                   requests.
  15. #
  16. #   Functions:      new
  17. #                   version
  18. #                   url
  19. #                   product_tokens
  20. #                   started
  21. #                   path
  22. #                   host
  23. #                   port
  24. #                   requests
  25. #                   response
  26. #                   compress
  27. #                   compress_thresh
  28. #                   compress_re
  29. #                   message_file_thresh
  30. #                   message_temp_dir
  31. #                   xpl_path
  32. #                   add_method
  33. #                   method_from_file
  34. #                   get_method
  35. #                   server_loop
  36. #                   post_configure_hook
  37. #                   pre_loop_hook
  38. #                   process_request
  39. #                   dispatch
  40. #                   call
  41. #                   add_default_methods
  42. #                   add_methods_in_dir
  43. #                   delete_method
  44. #                   list_methods
  45. #                   share_methods
  46. #                   copy_methods
  47. #                   timeout
  48. #
  49. #   Libraries:      AutoLoader
  50. #                   HTTP::Daemon (conditionally)
  51. #                   HTTP::Response
  52. #                   HTTP::Status
  53. #                   URI
  54. #                   RPC::XML
  55. #                   RPC::XML::Parser
  56. #                   RPC::XML::Procedure
  57. #
  58. #   Global Consts:  $VERSION
  59. #                   $INSTALL_DIR
  60. #
  61. ###############################################################################
  62.  
  63. package RPC::XML::Server;
  64.  
  65. use 5.005;
  66. use strict;
  67. use vars qw($VERSION @ISA $INSTANCE $INSTALL_DIR @XPL_PATH
  68.             $IO_SOCKET_SSL_HACK_NEEDED);
  69.  
  70. use Carp 'carp';
  71. use AutoLoader 'AUTOLOAD';
  72. use File::Spec;
  73.  
  74. BEGIN {
  75.     $INSTALL_DIR = (File::Spec->splitpath(__FILE__))[1];
  76.     @XPL_PATH = ($INSTALL_DIR, File::Spec->curdir);
  77.  
  78.     # For now, I have an ugly hack in place to make the functionality that
  79.     # runs under HTTP::Daemon/Net::Server work better with SSL. This flag
  80.     # starts out true, then gets set to false the first time the hack is
  81.     # applied, so that it doesn't get repeated over and over...
  82.     $IO_SOCKET_SSL_HACK_NEEDED = 1;
  83. }
  84.  
  85. use HTTP::Status;
  86. require HTTP::Response;
  87. require URI;
  88.  
  89. use RPC::XML 'bytelength';
  90. require RPC::XML::Parser;
  91. require RPC::XML::Procedure;
  92.  
  93. $VERSION = '1.48';
  94.  
  95. ###############################################################################
  96. #
  97. #   Sub Name:       new
  98. #
  99. #   Description:    Create a new RPC::XML::Server object. This entails getting
  100. #                   a HTTP::Daemon object, saving several internal values, and
  101. #                   other operations.
  102. #
  103. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  104. #                   $class    in      scalar    Ref or string for the class
  105. #                   %args     in      hash      Additional arguments
  106. #
  107. #   Returns:        Success:    object reference
  108. #                   Failure:    error string
  109. #
  110. ###############################################################################
  111. sub new
  112. {
  113.     my $class = shift;
  114.     my %args = @_;
  115.  
  116.     my ($self, $http, $resp, $host, $port, $queue, $path, $URI, $srv_name,
  117.         $srv_version, $timeout);
  118.  
  119.     $class = ref($class) || $class;
  120.     $self = bless {}, $class;
  121.  
  122.     $srv_version = $args{server_version} || $self->version;
  123.     $srv_name    = $args{server_name}    || $class;
  124.     $self->{__version} = "$srv_name/$srv_version";
  125.  
  126.     if ($args{no_http})
  127.     {
  128.         $self->{__host} = $args{host} || '';
  129.         $self->{__port} = $args{port} || '';
  130.         delete @args{qw(host port)};
  131.     }
  132.     else
  133.     {
  134.         require HTTP::Daemon;
  135.  
  136.         $host = $args{host}   || '';
  137.         $port = $args{port}   || '';
  138.         $queue = $args{queue} || 5;
  139.         $http = HTTP::Daemon->new(Reuse => 1,
  140.                                   ($host ? (LocalHost => $host) : ()),
  141.                                   ($port ? (LocalPort => $port) : ()),
  142.                                   ($queue ? (Listen => $queue)  : ()));
  143.         return "${class}::new: Unable to create HTTP::Daemon object"
  144.             unless $http;
  145.         $URI = URI->new($http->url);
  146.         $self->{__host} = $URI->host;
  147.         $self->{__port} = $URI->port;
  148.         $self->{__daemon} = $http;
  149.  
  150.         # Remove those we've processed
  151.         delete @args{qw(host port queue)};
  152.     }
  153.     $resp = HTTP::Response->new();
  154.     return "${class}::new: Unable to create HTTP::Response object"
  155.         unless $resp;
  156.     $resp->header(# This is essentially the same string returned by the
  157.                   # default "identity" method that may be loaded from a
  158.                   # XPL file. But it hasn't been loaded yet, and may not
  159.                   # be, hence we set it here (possibly from option values)
  160.                   RPC_Server   => $self->{__version},
  161.                   RPC_Encoding => 'XML-RPC',
  162.                   # Set any other headers as well
  163.                   Accept       => 'text/xml');
  164.     $resp->content_type('text/xml');
  165.     $resp->code(RC_OK);
  166.     $resp->message('OK');
  167.     $self->{__response} = $resp;
  168.  
  169.     $self->{__path}            = $args{path} || '';
  170.     $self->{__started}         = 0;
  171.     $self->{__method_table}    = {};
  172.     $self->{__requests}        = 0;
  173.     $self->{__auto_methods}    = $args{auto_methods} || 0;
  174.     $self->{__auto_updates}    = $args{auto_updates} || 0;
  175.     $self->{__debug}           = $args{debug} || 0;
  176.     $self->{__parser}          = RPC::XML::Parser->new($args{parser} ?
  177.                                                        @{$args{parser}} : ());
  178.     $self->{__xpl_path}        = $args{xpl_path} || [];
  179.     $self->{__timeout}         = $args{timeout}  || 10;
  180.  
  181.     $self->add_default_methods unless ($args{no_default});
  182.     $self->{__compress} = '';
  183.     unless ($args{no_compress})
  184.     {
  185.         eval "require Compress::Zlib";
  186.         $self->{__compress} = $@ ? '' : 'deflate';
  187.         # Add some more headers to the default response object for compression.
  188.         # It looks wasteful to keep using the hash key, but it makes it easier
  189.         # to change the string in just one place (above) if I have to.
  190.         $resp->header(Accept_Encoding => $self->{__compress})
  191.             if $self->{__compress};
  192.         $self->{__compress_thresh} = $args{compress_thresh} || 4096;
  193.         # Yes, I know this is redundant. It's for future expansion/flexibility.
  194.         $self->{__compress_re} =
  195.             $self->{__compress} ? qr/$self->{__compress}/ : qr/deflate/;
  196.     }
  197.  
  198.     # Parameters to control the point at which messages are shunted to temp
  199.     # files due to size, and where to home the temp files. Start with a size
  200.     # threshhold of 1Meg and no specific dir (which will fall-through to the
  201.     # tmpdir() method of File::Spec).
  202.     $self->{__message_file_thresh} = $args{message_file_thresh} || 1048576;
  203.     $self->{__message_temp_dir}    = $args{message_temp_dir}    || '';
  204.  
  205.     # Remove the args we've already dealt with directly
  206.     delete @args{qw(no_default no_http debug path server_name server_version
  207.                     no_compress compress_thresh parser message_file_thresh
  208.                     message_temp_dir)};
  209.     # Copy the rest over untouched
  210.     $self->{$_} = $args{$_} for (keys %args);
  211.  
  212.     $self;
  213. }
  214.  
  215. # Most of these tiny subs are accessors to the internal hash keys. They not
  216. # only control access to the internals, they ease sub-classing.
  217.  
  218. sub version { $RPC::XML::Server::VERSION }
  219.  
  220. sub INSTALL_DIR { $INSTALL_DIR }
  221.  
  222. sub url
  223. {
  224.     my $self = shift;
  225.  
  226.     return $self->{__daemon}->url if $self->{__daemon};
  227.     return undef unless (my $host = $self->host);
  228.  
  229.     my $path = $self->path;
  230.     my $port = $self->port;
  231.     if ($port == 443)
  232.     {
  233.         return "https://$host$path";
  234.     }
  235.     elsif ($port == 80)
  236.     {
  237.         return "http://$host$path";
  238.     }
  239.     else
  240.     {
  241.         return "http://$host:$port$path";
  242.     }
  243. }
  244.  
  245. sub product_tokens
  246. {
  247.     sprintf "%s/%s", (ref $_[0] || $_[0]), $_[0]->version;
  248. }
  249.  
  250. # This fetches/sets the internal "started" timestamp. Unlike the other
  251. # plain-but-mutable attributes, this isn't set to the passed-value but
  252. # rather a non-null argument sets it from the current time.
  253. sub started
  254. {
  255.     my ($self, $set) = @_;
  256.  
  257.     my $old = $self->{__started} || 0;
  258.     $self->{__started} = time if $set;
  259.  
  260.     $old;
  261. }
  262.  
  263. BEGIN
  264. {
  265.     no strict 'refs';
  266.     my $method;
  267.  
  268.     # These are mutable member values for which the logic only differs in
  269.     # the name of the field to modify:
  270.     for $method (qw(compress_thresh message_file_thresh message_temp_dir))
  271.     {
  272.         *$method = sub {
  273.             my ($self, $set) = @_;
  274.  
  275.             my $old = $self->{"__$method"};
  276.             $self->{"__$method"} = $set if (defined $set);
  277.  
  278.             $old;
  279.         }
  280.     }
  281.  
  282.     # These are immutable member values, so this simple block applies to all
  283.     for $method (qw(path host port requests response compress compress_re
  284.                        parser))
  285.     {
  286.         *$method = sub { shift->{"__$method"} }
  287.     }
  288. }
  289.  
  290. # Get/set the search path for XPL files
  291. sub xpl_path
  292. {
  293.     my $self = shift;
  294.     my $ret = $self->{__xpl_path};
  295.  
  296.     $self->{__xpl_path} = $_[0] if ($_[0] and ref($_[0]) eq 'ARRAY');
  297.     $ret;
  298. }
  299.  
  300. ###############################################################################
  301. #
  302. #   Sub Name:       add_method
  303. #
  304. #   Description:    Add a funtion-to-method mapping to the server object.
  305. #
  306. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  307. #                   $self     in      ref       Object to add to
  308. #                   $meth     in      scalar    Hash ref of data or file name
  309. #
  310. #   Returns:        Success:    $self
  311. #                   Failure:    error string
  312. #
  313. ###############################################################################
  314. sub add_method
  315. {
  316.     my $self = shift;
  317.     my $meth = shift;
  318.  
  319.     my ($name, $val);
  320.  
  321.     my $me = ref($self) . '::add_method';
  322.  
  323.     if (! ref($meth))
  324.     {
  325.         $val = $self->method_from_file($meth);
  326.         if (! ref($val))
  327.         {
  328.             return "$me: Error loading from file $meth: $val";
  329.         }
  330.         else
  331.         {
  332.             $meth = $val;
  333.         }
  334.     }
  335.     elsif (ref($meth) eq 'HASH')
  336.     {
  337.         my $class = 'RPC::XML::' . ucfirst ($meth->{type} || 'method');
  338.         $meth = $class->new($meth);
  339.     }
  340.     elsif (! UNIVERSAL::isa($meth, 'RPC::XML::Procedure'))
  341.     {
  342.         return "$me: Method argument must be a file name, a hash " .
  343.             'reference or an object derived from RPC::XML::Procedure';
  344.     }
  345.  
  346.     # Do some sanity-checks
  347.     return "$me: Method missing required data; check name, code and/or " .
  348.         'signature' unless $meth->is_valid;
  349.  
  350.     $name = $meth->name;
  351.     $self->{__method_table}->{$name} = $meth;
  352.  
  353.     $self;
  354. }
  355.  
  356. 1;
  357.  
  358. =pod
  359.  
  360. =head1 NAME
  361.  
  362. RPC::XML::Server - A sample server implementation based on RPC::XML
  363.  
  364. =head1 SYNOPSIS
  365.  
  366.     use RPC::XML::Server;
  367.  
  368.     ...
  369.     $srv = RPC::XML::Server->new(port => 9000);
  370.     # Several of these, most likely:
  371.     $srv->add_method(...);
  372.     ...
  373.     $srv->server_loop; # Never returns
  374.  
  375. =head1 DESCRIPTION
  376.  
  377. This is a sample XML-RPC server built upon the B<RPC::XML> data classes, and
  378. using B<HTTP::Daemon> and B<HTTP::Response> for the communication layer.
  379.  
  380. =head1 USAGE
  381.  
  382. Use of the B<RPC::XML::Server> is based on an object model. A server is
  383. instantiated from the class, methods (subroutines) are made public by adding
  384. them through the object interface, and then the server object is responsible
  385. for dispatching requests (and possibly for the HTTP listening, as well).
  386.  
  387. =head2 Static Methods
  388.  
  389. These methods are static to the package, and are used to provide external
  390. access to internal settings:
  391.  
  392. =over 4
  393.  
  394. =item INSTALL_DIR
  395.  
  396. Returns the directory that this module is installed into. This is used by
  397. methods such as C<add_default_methods> to locate the XPL files that are
  398. shipped with the distribution.
  399.  
  400. =item version
  401.  
  402. Returns the version string associated with this package.
  403.  
  404. =item product_tokens
  405.  
  406. This returns the identifying string for the server, in the format
  407. C<NAME/VERSION> consistent with other applications such as Apache and
  408. B<LWP>. It is provided here as part of the compatibility with B<HTTP::Daemon>
  409. that is required for effective integration with B<Net::Server>.
  410.  
  411. =back
  412.  
  413. =head2 Methods
  414.  
  415. The following are object (non-static) methods. Unless otherwise explicitly
  416. noted, all methods return the invoking object reference upon success, and a
  417. non-reference error string upon failure.
  418.  
  419. See L</Content Compression> below for details of how the server class manages
  420. gzip-based compression and expansion of messages.
  421.  
  422. =over 4
  423.  
  424. =item new(OPTIONS)
  425.  
  426. Creates a new object of the class and returns the blessed reference. Depending
  427. on the options, the object will contain some combination of an HTTP listener,
  428. a pre-populated B<HTTP::Response> object, a B<RPC::XML::Parser> object, and
  429. a dispatch table with the set of default methods pre-loaded. The options that
  430. B<new> accepts are passed as a hash of key/value pairs (not a hash reference).
  431. The accepted options are:
  432.  
  433. =over 4
  434.  
  435. =item B<no_http>
  436.  
  437. If passed with a C<true> value, prevents the creation and storage of the
  438. B<HTTP::Daemon> object. This allows for deployment of a server object in other
  439. environments. Note that if this is set, the B<server_loop> method described
  440. below will silently attempt to use the B<Net::Server> module.
  441.  
  442. =item B<no_default>
  443.  
  444. If passed with a C<true> value, prevents the loading of the default methods
  445. provided with the B<RPC::XML> distribution. These may be later loaded using
  446. the B<add_default_methods> interface described later. The methods themselves
  447. are described below (see L<"The Default Methods Provided">).
  448.  
  449. =item B<path>
  450.  
  451. =item B<host>
  452.  
  453. =item B<port>
  454.  
  455. =item B<queue>
  456.  
  457. These four are specific to the HTTP-based nature of the server.  The B<path>
  458. argument sets the additional URI path information that clients would use to
  459. contact the server.  Internally, it is not used except in outgoing status and
  460. introspection reports.  The B<host>, B<port> and B<queue> arguments are passed
  461. to the B<HTTP::Daemon> constructor if they are passed. They set the hostname,
  462. TCP/IP port, and socket listening queue, respectively. They may also be used
  463. if the server object tries to use B<Net::Server> as an alternative server
  464. core.
  465.  
  466. =item B<xpl_path>
  467.  
  468. If you plan to add methods to the server object by passing filenames to the
  469. C<add_method> call, this argument may be used to specify one or more
  470. additional directories to be searched when the passed-in filename is a
  471. relative path. The value for this must be an array reference. See also
  472. B<add_method> and B<xpl_path>, below.
  473.  
  474. =item B<timeout>
  475.  
  476. Specify a value (in seconds) for the B<HTTP::Daemon> server to use as a
  477. timeout value when reading request data from an inbound connection. The
  478. default value is 10 seconds. This value is not used except by B<HTTP::Daemon>.
  479.  
  480. =item B<auto_methods>
  481.  
  482. If specified and set to a true value, enables the automatic searching for a
  483. requested remote method that is unknown to the server object handling the
  484. request. If set to "no" (or not set at all), then a request for an unknown
  485. function causes the object instance to report an error. If the routine is
  486. still not found, the error is reported. Enabling this is a security risk, and
  487. should only be permitted by a server administrator with fully informed
  488. acknowledgement and consent.
  489.  
  490. =item B<auto_updates>
  491.  
  492. If specified and set to a "true" value, enables the checking of the
  493. modification time of the file from which a method was originally loaded. If
  494. the file has changed, the method is re-loaded before execution is handed
  495. off. As with the auto-loading of methods, this represents a security risk, and
  496. should only be permitted by a server administrator with fully informed
  497. acknowledgement and consent.
  498.  
  499. =item B<parser>
  500.  
  501. If this parameter is passed, the value following it is expected to be an
  502. array reference. The contents of that array are passed to the B<new> method
  503. of the B<RPC::XML::Parser> object that the server object caches for its use.
  504. See the B<RPC::XML::Parser> manual page for a list of recognized parameters
  505. to the constructor.
  506.  
  507. =item B<message_file_thresh>
  508.  
  509. If this key is passed, the value associated with it is assumed to be a
  510. numerical limit to the size of in-memory messages. Any out-bound request that
  511. would be larger than this when stringified is instead written to an anonynous
  512. temporary file, and spooled from there instead. This is useful for cases in
  513. which the request includes B<RPC::XML::base64> objects that are themselves
  514. spooled from file-handles. This test is independent of compression, so even
  515. if compression of a request would drop it below this threshhold, it will be
  516. spooled anyway. The file itself is unlinked after the file-handle is created,
  517. so once it is freed the disk space is immediately freed.
  518.  
  519. =item B<message_temp_dir>
  520.  
  521. If a message is to be spooled to a temporary file, this key can define a
  522. specific directory in which to open those files. If this is not given, then
  523. the C<tmpdir> method from the B<File::Spec> package is used, instead.
  524.  
  525. =back
  526.  
  527. Any other keys in the options hash not explicitly used by the constructor are
  528. copied over verbatim onto the object, for the benefit of sub-classing this
  529. class. All internal keys are prefixed with C<__> to avoid confusion. Feel
  530. free to use this prefix only if you wish to re-introduce confusion.
  531.  
  532. =item url
  533.  
  534. This returns the HTTP URL that the server will be responding to, when it is in
  535. the connection-accept loop. If the server object was created without a
  536. built-in HTTP listener, then this method returns C<undef>.
  537.  
  538. =item requests
  539.  
  540. Returns the number of requests this server object has marshalled. Note that in
  541. multi-process environments (such as Apache or Net::Server::PreFork) the value
  542. returned will only reflect the messages dispatched by the specific process
  543. itself.
  544.  
  545. =item response
  546.  
  547. Each instance of this class (and any subclasses that do not completely
  548. override the C<new> method) creates and stores an instance of
  549. B<HTTP::Response>, which is then used by the B<HTTP::Daemon> or B<Net::Server>
  550. processing loops in constructing the response to clients. The response object
  551. has all common headers pre-set for efficiency. This method returns a reference
  552. to that object.
  553.  
  554. =item started([BOOL])
  555.  
  556. Gets and possibly sets the clock-time when the server starts accepting
  557. connections. If a value is passed that evaluates to true, then the current
  558. clock time is marked as the starting time. In either case, the current value
  559. is returned. The clock-time is based on the internal B<time> command of Perl,
  560. and thus is represented as an integer number of seconds since the system
  561. epoch. Generally, it is suitable for passing to either B<localtime> or to the
  562. C<time2iso8601> routine exported by the B<RPC::XML> package.
  563.  
  564. =item timeout(INT)
  565.  
  566. You can call this method to set the timeout of new connections after
  567. they are received.  This function returns the old timeout value.  If
  568. you pass in no value then it will return the old value without
  569. modifying the current value.  The default value is 10 seconds.
  570.  
  571. =item add_method(FILE | HASHREF | OBJECT)
  572.  
  573. =item add_proc(FILE | HASHREF | OBJECT)
  574.  
  575. This adds a new published method or procedure to the server object that
  576. invokes it. The new method may be specified in one of three ways: as a
  577. filename, a hash reference or an existing object (generally of either
  578. B<RPC::XML::Procedure> or B<RPC::XML::Method> classes).
  579.  
  580. If passed as a hash reference, the following keys are expected:
  581.  
  582. =over 4
  583.  
  584. =item B<name>
  585.  
  586. The published (externally-visible) name for the method.
  587.  
  588. =item B<version>
  589.  
  590. An optional version stamp. Not used internally, kept mainly for informative
  591. purposes.
  592.  
  593. =item B<hidden>
  594.  
  595. If passed and evaluates to a C<true> value, then the method should be hidden
  596. from any introspection API implementations. This parameter is optional, the
  597. default behavior being to make the method publically-visible.
  598.  
  599. =item B<code>
  600.  
  601. A code reference to the actual Perl subroutine that handles this method. A
  602. symbolic reference is not accepted. The value can be passed either as a
  603. reference to an existing routine, or possibly as a closure. See
  604. L</"How Methods are Called"> for the semantics the referenced subroutine must
  605. follow.
  606.  
  607. =item B<signature>
  608.  
  609. A list reference of the signatures by which this routine may be invoked. Every
  610. method has at least one signature. Though less efficient for cases of exactly
  611. one signature, a list reference is always used for sake of consistency.
  612.  
  613. =item B<help>
  614.  
  615. Optional documentation text for the method. This is the text that would be
  616. returned, for example, by a B<system.methodHelp> call (providing the server
  617. has such an externally-visible method).
  618.  
  619. =back
  620.  
  621. If a file is passed, then it is expected to be in the XML-based format,
  622. described in the B<RPC::XML::Procedure> manual (see L<RPC::XML::Procedure>).
  623. If the name passed is not an absolute pathname, then the file will be searched
  624. for in any directories specified when the object was instantiated, then in the
  625. directory into which this module was installed, and finally in the current
  626. working directory. If the operation fails, the return value will be a
  627. non-reference, an error message. Otherwise, the return value is the object
  628. reference.
  629.  
  630. The B<add_method> and B<add_proc> calls are essentialy identical unless called
  631. with hash references. Both files and objects contain the information that
  632. defines the type (method vs. procedure) of the funtionality to be added to the
  633. server. If B<add_method> is called with a file that describes a procedure, the
  634. resulting addition to the server object will be a B<RPC::XML::Procedure>
  635. object, not a method object.
  636.  
  637. For more on the creation and manipulation of procedures and methods as
  638. objects, see L<RPC::XML::Procedure>.
  639.  
  640. =item delete_method(NAME)
  641.  
  642. =item delete_proc(NAME)
  643.  
  644. Delete the named method or procedure from the calling object. Removes the
  645. entry from the internal table that the object maintains. If the method is
  646. shared across more than one server object (see L</share_methods>), then the
  647. underlying object for it will only be destroyed when the last server object
  648. releases it. On error (such as no method by that name known), an error string
  649. is returned.
  650.  
  651. The B<delete_proc> call is identical, supplied for the sake of symmetry. Both
  652. calls return the matched object regardless of its underlying type.
  653.  
  654. =item list_methods
  655.  
  656. =item list_procs
  657.  
  658. This returns a list of the names of methods and procedures the server current
  659. has published.  Note that the returned values are not the method objects, but
  660. rather the names by which they are externally known. The "hidden" status of a
  661. method is not consulted when this list is created; all methods and procedures
  662. known are listed. The list is not sorted in any specific order.
  663.  
  664. The B<list_procs> call is provided for symmetry. Both calls list all published
  665. routines on the calling server object, regardless of underlying type.
  666.  
  667. =item xpl_path([LISTREF])
  668.  
  669. Get and/or set the object-specific search path for C<*.xpl> files (files that
  670. specify methods) that are specified in calls to B<add_method>, above. If a
  671. list reference is passed, it is installed as the new path (each element of the
  672. list being one directory name to search). Regardless of argument, the current
  673. path is returned as a list reference. When a file is passed to B<add_method>,
  674. the elements of this path are searched first, in order, before the
  675. installation directory or the current working directory are searched.
  676.  
  677. =item get_method(NAME)
  678.  
  679. =item get_proc(NAME)
  680.  
  681. Returns a reference to an object of the class B<RPC::XML::Method> or
  682. B<RPC::XML::Procedure>, which is the current binding for the published method
  683. NAME. If there is no such method known to the server, then C<undef> is
  684. returned. The object is implemented as a hash, and has the same key and value
  685. pairs as for C<add_method>, above. Thus, the reference returned is suitable
  686. for passing back to C<add_method>. This facilitates temporary changes in what
  687. a published name maps to. Note that this is a referent to the object as stored
  688. on the server object itself, and thus changes to it could affect the behavior
  689. of the server.
  690.  
  691. The B<get_proc> interface is provided for symmetry.
  692.  
  693. =item server_loop(HASH)
  694.  
  695. Enters the connection-accept loop, which generally does not return. This is
  696. the C<accept()>-based loop of B<HTTP::Daemon> if the object was created with
  697. an instance of that class as a part. Otherwise, this enters the run-loop of
  698. the B<Net::Server> class. It listens for requests, and marshalls them out via
  699. the C<dispatch> method described below. It answers HTTP-HEAD requests
  700. immediately (without counting them on the server statistics) and efficiently
  701. by using a cached B<HTTP::Response> object.
  702.  
  703. Because infinite loops requiring a C<HUP> or C<KILL> signal to terminate are
  704. generally in poor taste, the B<HTTP::Daemon> side of this sets up a localized
  705. signal handler which causes an exit when triggered. By default, this is
  706. attached to the C<INT> signal. If the B<Net::Server> module is being used
  707. instead, it provides its own signal management.
  708.  
  709. The arguments, if passed, are interpreted as a hash of key/value options (not
  710. a hash reference, please note). For B<HTTP::Daemon>, only one is recognized:
  711.  
  712. =over 4
  713.  
  714. =item B<signal>
  715.  
  716. If passed, should be the traditional name for the signal that should be bound
  717. to the exit function. If desired, a reference to an array of signal names may
  718. be passed, in which case all signals will be given the same handler. The user
  719. is responsible for not passing the name of a non-existent signal, or one that
  720. cannot be caught. If the value of this argument is 0 (a C<false> value) or the
  721. string C<B<NONE>>, then the signal handler will I<not> be installed, and the
  722. loop may only be broken out of by killing the running process (unless other
  723. arrangements are made within the application).
  724.  
  725. =back
  726.  
  727. The options that B<Net::Server> responds to are detailed in the manual pages
  728. for that package. All options passed to C<server_loop> in this situation are
  729. passed unaltered to the C<run()> method in B<Net::Server>.
  730.  
  731. =item dispatch(REQUEST)
  732.  
  733. This is the server method that actually manages the marshalling of an incoming
  734. request into an invocation of a Perl subroutine. The parameter passed in may
  735. be one of: a scalar containing the full XML text of the request, a scalar
  736. reference to such a string, or a pre-constructed B<RPC::XML::request> object.
  737. Unless an object is passed, the text is parsed with any errors triggering an
  738. early exit. Once the object representation of the request is on hand, the
  739. parameter data is extracted, as is the method name itself. The call is sent
  740. along to the appropriate subroutine, and the results are collated into an
  741. object of the B<RPC::XML::response> class, which is returned. Any non-reference
  742. return value should be presumed to be an error string.
  743.  
  744. The dispatched method may communicate error in several ways.  First, any
  745. non-reference return value is presumed to be an error string, and is encoded
  746. and returned as an B<RPC::XML::fault> response.  The method is run under an
  747. C<eval()>, so errors conveyed by C<$@> are similarly encoded and returned.  As
  748. a special case, a method may explicitly C<die()> with a fault response, which
  749. is passed on unmodified.
  750.  
  751. =item add_default_methods([DETAILS])
  752.  
  753. This method adds all the default methods (those that are shipped with this
  754. extension) to the calling server object. The files are denoted by their
  755. C<*.xpl> extension, and are installed into the same directory as this
  756. B<Server.pm> file. The set of default methods are described below (see
  757. L<"The Default Methods Provided">).
  758.  
  759. If any names are passed as a list of arguments to this call, then only those
  760. methods specified are actually loaded. If the C<*.xpl> extension is absent on
  761. any of these names, then it is silently added for testing purposes. Note that
  762. the methods shipped with this package have file names without the leading
  763. C<status.> part of the method name. If the very first element of the list of
  764. arguments is C<except> (or C<-except>), then the rest of the list is
  765. treated as a set of names to I<not> load, while all others do get read. The
  766. B<Apache::RPC::Server> module uses this to prevent the loading of the default
  767. C<system.status> method while still loading all the rest of the defaults. (It
  768. then provides a more Apache-centric status method.)
  769.  
  770. Note that there is no symmetric call in this case. The provided API is
  771. implemented as methods, and thus only this interface is provided.
  772.  
  773. =item add_methods_in_dir(DIR [, DETAILS])
  774.  
  775. =item add_procs_in_dir(DIR [, DETAILS])
  776.  
  777. This is exactly like B<add_default_methods> above, save that the caller
  778. specifies which directory to scan for C<*.xpl> files. In fact, the
  779. B<add_default_methods> routine simply calls this routine with the installation
  780. directory as the first argument. The definition of the additional arguments is
  781. the same as above.
  782.  
  783. B<add_procs_in_dir> is provided for symmetry.
  784.  
  785. =item share_methods(SERVER, NAMES)
  786.  
  787. =item share_procs(SERVER, NAMES)
  788.  
  789. The calling server object shares the methods and/or procedures listed in
  790. B<NAMES> with the source-server passed as the first object. The source must
  791. derive from this package in order for this operation to be permitted. At least
  792. one method must be specified, and all are specified by name (not by object
  793. refernce). Both objects will reference the same exact B<RPC::XML::Procedure>
  794. (or B<Method>, or derivative thereof) object in this case, meaning that
  795. call-statistics and the like will reflect the combined data. If one or more of
  796. the passed names are not present on the source server, an error message is
  797. returned and none are copied to the calling object.
  798.  
  799. Alternately, one or more of the name parameters passed to this call may be
  800. regular-expression objects (the result of the B<qr> operator). Any of these
  801. detected are applied against the list of all available methods known to the
  802. source server. All matching ones are inserted into the list (the list is pared
  803. for redundancies in any case). This allows for easier addition of whole
  804. classes such as those in the C<system.*> name space (via B<C<qr/^system\./>>),
  805. for example. There is no substring matching provided. Names listed in the
  806. parameters to this routine must be either complete strings or regular
  807. expressions.
  808.  
  809. The B<share_procs> interface is provided for symmetry.
  810.  
  811. =item copy_methods(SERVER, NAMES)
  812.  
  813. =item copy_procs(SERVER, NAMES)
  814.  
  815. This behaves like the method B<share_methods> above, with the exception that
  816. the calling object is given a clone of each method, rather than referencing
  817. the same exact method as the source server. The code reference part of the
  818. method is shared between the two, but all other data are copied (including a
  819. fresh copy of any list references used) into a completely new
  820. B<RPC::XML::Procedure> (or derivative) object, using the C<clone()> method
  821. from that class. Thus, while the calling object has the same methods
  822. available, and is re-using existing code in the Perl runtime, the method
  823. objects (and hence the statistics and such) are kept separate. As with the
  824. above, an error is flagged if one or more are not found.
  825.  
  826. This routine also accepts regular-expression objects with the same behavior
  827. and limitations. Again, B<copy_procs> is simply provided for symmetry.
  828.  
  829. =back
  830.  
  831. =head2 Specifying Server-Side Remote Methods
  832.  
  833. Specifying the methods themselves can be a tricky undertaking. Some packages
  834. (in other languages) delegate a specific class to handling incoming requests.
  835. This works well, but it can lead to routines not intended for public
  836. availability to in fact be available. There are also issues around the access
  837. that the methods would then have to other resources within the same running
  838. system.
  839.  
  840. The approach taken by B<RPC::XML::Server> (and the B<Apache::RPC::Server>
  841. subclass of it) require that methods be explicitly published in one of the
  842. several ways provided. Methods may be added directly within code by using
  843. C<add_method> as described above, with full data provided for the code
  844. reference, signature list, etc. The C<add_method> technique can also be used
  845. with a file that conforms to a specific XML-based format (detailed in the
  846. manual page for the B<RPC::XML::Procedure> class, see L<RPC::XML::Procedure>).
  847. Entire directories of files may be added using C<add_methods_in_dir>, which
  848. merely reads the given directory for files that appear to be method
  849. definitions.
  850.  
  851. =head2 How Methods Are Called
  852.  
  853. When a routine is called via the server dispatcher, it is called with the
  854. arguments that the client request passed. Depending on whether the routine is
  855. considered a "procedure" or a "method", there may be an extra argument at the
  856. head of the list. The extra argument is present when the routine being
  857. dispatched is part of a B<RPC::XML::Method> object. The extra argument is a
  858. reference to a B<RPC::XML::Server> object (or a subclass thereof). This is
  859. derived from a hash reference, and will include these special keys:
  860.  
  861. =over 4
  862.  
  863. =item method_name
  864.  
  865. This is the name by which the method was called in the client. Most of the
  866. time, this will probably be consistent for all calls to the server-side
  867. method. But it does not have to be, hence the passing of the value.
  868.  
  869. =item signature
  870.  
  871. This is the signature that was used, when dispatching. Perl has a liberal
  872. view of lists and scalars, so it is not always clear what arguments the client
  873. specifically has in mind when calling the method. The signature is an array
  874. reference containing one or more datatypes, each a simple string. The first
  875. of the datatypes specifies the expected return type. The remainder (if any)
  876. refer to the arguments themselves.
  877.  
  878. =item peeraddr
  879.  
  880. This is the address part of a packed B<SOCKADDR_IN> structure, as returned by
  881. L<Socket/pack_sockaddr_in>, which contains the address of the client that has
  882. connected and made the current request. This is provided "raw" in case you
  883. need it. While you could re-create it from C<peerhost>, it is readily
  884. available in both this server environment and the B<Apache::RPC::Server>
  885. environment and thus included for convenience.
  886.  
  887. =item peerhost
  888.  
  889. This is the address of the remote (client) end of the socket, in C<x.x.x.x>
  890. (dotted-quad) format. If you wish to look up the clients host-name, you
  891. can use this to do so or utilize the encoded structure above directly.
  892.  
  893. =item peerport
  894.  
  895. Lastly, this is the port of the remote (client) end of the socket, taken
  896. from the B<SOCKADDR_IN> structure.
  897.  
  898. =back
  899.  
  900. Those keys should only be referenced within method code itself, as they are
  901. not set on the server object outside of that context.
  902.  
  903. Note that by passing the server object reference first, method-classed
  904. routines are essentially expected to behave as actual methods of the server
  905. class, as opposed to ordinary functions. Of course, they can also discard the
  906. initial argument completely.
  907.  
  908. The routines should not make (excessive) use of global variables, for obvious
  909. reasons. When the routines are loaded from XPL files, the code is created as a
  910. closure that forces execution in the B<RPC::XML::Procedure> package. If the
  911. code element of a procedure/method is passed in as a direct code reference by
  912. one of the other syntaxes allowed by the constructor, the package may well be
  913. different. Thus, routines should strive to be as localized as possible,
  914. independant of specific namespaces. If a group of routines are expected to
  915. work in close concert, each should explicitly set the namespace with a
  916. C<package> declaration as the first statement within the routines themselves.
  917.  
  918. =head2 The Default Methods Provided
  919.  
  920. The following methods are provided with this package, and are the ones
  921. installed on newly-created server objects unless told not to. These are
  922. identified by their published names, as they are compiled internally as
  923. anonymous subroutines and thus cannot be called directly:
  924.  
  925. =over 4
  926.  
  927. =item B<system.identity>
  928.  
  929. Returns a B<string> value identifying the server name, version, and possibly a
  930. capability level. Takes no arguments.
  931.  
  932. =item B<system.introspection>
  933.  
  934. Returns a series of B<struct> objects that give overview documentation of one
  935. or more of the published methods. It may be called with a B<string>
  936. identifying a single routine, in which case the return value is a
  937. B<struct>. It may be called with an B<array> of B<string> values, in which
  938. case an B<array> of B<struct> values, one per element in, is returned. Lastly,
  939. it may be called with no input parameters, in which case all published
  940. routines are documented.  Note that routines may be configured to be hidden
  941. from such introspection queries.
  942.  
  943. =item B<system.listMethods>
  944.  
  945. Returns a list of the published methods or a subset of them as an B<array> of
  946. B<string> values. If called with no parameters, returns all (non-hidden)
  947. method names. If called with a single B<string> pattern, returns only those
  948. names that contain the string as a substring of their name (case-sensitive,
  949. and this is I<not> a regular expression evaluation).
  950.  
  951. =item B<system.methodHelp>
  952.  
  953. Takes either a single method name as a B<string>, or a series of them as an
  954. B<array> of B<string>. The return value is the help text for the method, as
  955. either a B<string> or B<array> of B<string> value. If the method(s) have no
  956. help text, the string will be null.
  957.  
  958. =item B<system.methodSignature>
  959.  
  960. As above, but returns the signatures that the method accepts, as B<array> of
  961. B<string> representations. If only one method is requests via a B<string>
  962. parameter, then the return value is the corresponding array. If the parameter
  963. in is an B<array>, then the returned value will be an B<array> of B<array> of
  964. B<string>.
  965.  
  966. =item B<system.multicall>
  967.  
  968. This is a simple implementation of composite function calls in a single
  969. request. It takes an B<array> of B<struct> values. Each B<struct> has at least
  970. a C<methodName> member, which provides the name of the method to call. If
  971. there is also a C<params> member, it refers to an B<array> of the parameters
  972. that should be passed to the call.
  973.  
  974. =item B<system.status>
  975.  
  976. Takes no arguments and returns a B<struct> containing a number of system
  977. status values including (but not limited to) the current time on the server,
  978. the time the server was started (both of these are returned in both ISO 8601
  979. and UNIX-style integer formats), number of requests dispatched, and some
  980. identifying information (hostname, port, etc.).
  981.  
  982. =back
  983.  
  984. In addition, each of these has an accompanying help file in the C<methods>
  985. sub-directory of the distribution.
  986.  
  987. These methods are installed as C<*.xpl> files, which are generated from files
  988. in the C<methods> directory of the distribution using the B<make_method> tool
  989. (see L<make_method>). The files there provide the Perl code that implements
  990. these, their help files and other information.
  991.  
  992. =head2 Content Compression
  993.  
  994. The B<RPC::XML::Server> class now supports compressed messages, both incoming
  995. and outgoing. If a client indicates that it can understand compressed content,
  996. the server will use the B<Compress::Zlib> (available from CPAN) module, if
  997. available, to compress any outgoing messages above a certain threshhold in
  998. size (the default threshhold is set to 4096 bytes). The following methods are
  999. all related to the compression support within the server class:
  1000.  
  1001. =over 4
  1002.  
  1003. =item compress
  1004.  
  1005. Returns a false value if compression is not available to the server object.
  1006. This is based on the availability of the B<Compress::Zlib> module at start-up
  1007. time, and cannot be changed.
  1008.  
  1009. =item compress_thresh([MIN_LIMIT])
  1010.  
  1011. Return or set the compression threshhold value. Messages smaller than this
  1012. size in bytes will not be compressed, even when compression is available, to
  1013. save on CPU resources. If a value is passed, it becomes the new limit and the
  1014. old value is returned.
  1015.  
  1016. =back
  1017.  
  1018. =head2 Spooling Large Messages
  1019.  
  1020. If the server anticipates handling large out-bound messages (for example, if
  1021. the hosted code returns large Base64 values pre-encoded from file handles),
  1022. the C<message_file_thresh> and C<message_temp_dir> settings may be used in a
  1023. manner similar to B<RPC::XML::Client>. Specifically, the threshhold is used to
  1024. determine when a message should be spooled to a filehandle rather than made
  1025. into an in-memory string (the B<RPC::XML::base64> type can use a filehandle,
  1026. thus eliminating the need for the data to ever be completely in memory). An
  1027. anonymous temporary file is used for these operations.
  1028.  
  1029. Note that the message size is checked before compression is applied, since the
  1030. size of the compressed output cannot be known until the full message is
  1031. examined. It is possible that a message will be spooled even if its compressed
  1032. size is below the threshhold, if the uncompressed size exceeds the threshhold.
  1033.  
  1034. =over 4
  1035.  
  1036. =item message_file_thresh
  1037.  
  1038. =item message_temp_dir
  1039.  
  1040. These methods may be used to retrieve or alter the values of the given keys
  1041. as defined earlier for the C<new> method.
  1042.  
  1043. =back
  1044.  
  1045. =head1 DIAGNOSTICS
  1046.  
  1047. Unless explicitly stated otherwise, all methods return some type of reference
  1048. on success, or an error string on failure. Non-reference return values should
  1049. always be interpreted as errors unless otherwise noted.
  1050.  
  1051. =head1 CAVEATS
  1052.  
  1053. This began as a reference implementation in which clarity of process and
  1054. readability of the code took precedence over general efficiency. It is now
  1055. being maintained as production code, but may still have parts that could be
  1056. written more efficiently.
  1057.  
  1058. =head1 CREDITS
  1059.  
  1060. The B<XML-RPC> standard is Copyright (c) 1998-2001, UserLand Software, Inc.
  1061. See <http://www.xmlrpc.com> for more information about the B<XML-RPC>
  1062. specification. A helpful patch was sent in by Tino Wuensche to fix problems
  1063. in the signal-setting and signal-catching code in server_loop().
  1064.  
  1065. =head1 LICENSE
  1066.  
  1067. This module and the code within are released under the terms of the Artistic
  1068. License 2.0
  1069. (http://www.opensource.org/licenses/artistic-license-2.0.php). This code may
  1070. be redistributed under either the Artistic License or the GNU Lesser General
  1071. Public License (LGPL) version 2.1
  1072. (http://www.opensource.org/licenses/lgpl-license.php).
  1073.  
  1074. =head1 SEE ALSO
  1075.  
  1076. L<RPC::XML>, L<RPC::XML::Client>, L<RPC::XML::Parser>
  1077.  
  1078. =head1 AUTHOR
  1079.  
  1080. Randy J. Ray <rjray@blackperl.com>
  1081.  
  1082. =cut
  1083.  
  1084. __END__
  1085.  
  1086. ###############################################################################
  1087. #
  1088. #   Sub Name:       add_proc
  1089. #
  1090. #   Description:    This filters through to add_method, but unlike the other
  1091. #                   front-ends defined later, this one may have to alter the
  1092. #                   data in one type of calling-convention.
  1093. #
  1094. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1095. #                   $self     in      ref       Object reference
  1096. #                   $meth     in      scalar    Procedure to add
  1097. #
  1098. #   Returns:        threads through to add_method
  1099. #
  1100. ###############################################################################
  1101. sub add_proc
  1102. {
  1103.     my ($self, $meth) = @_;
  1104.  
  1105.     # Anything else but a hash-reference goes through unaltered
  1106.     $meth->{type} = 'procedure' if (ref($meth) eq 'HASH');
  1107.  
  1108.     $self->add_method($meth);
  1109. }
  1110.  
  1111. ###############################################################################
  1112. #
  1113. #   Sub Name:       method_from_file
  1114. #
  1115. #   Description:    Create a RPC::XML::Procedure (or ::Method) object from the
  1116. #                   passed-in file name, using the object's search path if the
  1117. #                   name is not already absolute.
  1118. #
  1119. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1120. #                   $self     in      ref       Object of this class
  1121. #                   $file     in      scalar    Name of file to load
  1122. #
  1123. #   Returns:        Success:    Method-object reference
  1124. #                   Failure:    error message
  1125. #
  1126. ###############################################################################
  1127. sub method_from_file
  1128. {
  1129.     my $self = shift;
  1130.     my $file = shift;
  1131.  
  1132.     unless (File::Spec->file_name_is_absolute($file))
  1133.     {
  1134.         my ($path, @path);
  1135.         push(@path, @{$self->xpl_path}) if (ref $self);
  1136.         for (@path, @XPL_PATH)
  1137.         {
  1138.             $path = File::Spec->catfile($_, $file);
  1139.             if (-e $path) { $file = File::Spec->canonpath($path); last; }
  1140.         }
  1141.     }
  1142.     # Just in case it still didn't appear in the path, we really want an
  1143.     # absolute path:
  1144.     $file = File::Spec->rel2abs($file)
  1145.         unless (File::Spec->file_name_is_absolute($file));
  1146.  
  1147.     RPC::XML::Procedure::new(undef, $file);
  1148. }
  1149.  
  1150. # Same as above, but for name-symmetry
  1151. sub proc_from_file { shift->method_from_file(@_) }
  1152.  
  1153. ###############################################################################
  1154. #
  1155. #   Sub Name:       get_method
  1156. #
  1157. #   Description:    Get the current binding for the remote-side method $name.
  1158. #                   Returns undef if the method is not defined for the server
  1159. #                   instance.
  1160. #
  1161. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1162. #                   $self     in      ref       Class instance
  1163. #                   $name     in      scalar    Name of the method being looked
  1164. #                                                 up
  1165. #
  1166. #   Returns:        Success:    Method-class reference
  1167. #                   Failure:    error string
  1168. #
  1169. ###############################################################################
  1170. sub get_method
  1171. {
  1172.     my $self = shift;
  1173.     my $name = shift;
  1174.  
  1175.     my $meth = $self->{__method_table}->{$name};
  1176.     unless (defined $meth)
  1177.     {
  1178.         if ($self->{__auto_methods})
  1179.         {
  1180.             # Try to load this dynamically on the fly, from any of the dirs
  1181.             # that are in this object's @xpl_path
  1182.             (my $loadname = $name) =~ s/^system\.//;
  1183.             $self->add_method("$loadname.xpl");
  1184.         }
  1185.         # If method is still not in the table, we were unable to load it
  1186.         return "Unknown method: $name"
  1187.             unless $meth = $self->{__method_table}->{$name};
  1188.     }
  1189.     # Check the mod-time of the file the method came from, if the test is on
  1190.     if ($self->{__auto_updates} && $meth->{file} &&
  1191.         ($meth->{mtime} < (stat $meth->{file})[9]))
  1192.     {
  1193.         my $ret = $meth->reload;
  1194.         return "Reload of method $name failed: $ret" unless ref($ret);
  1195.     }
  1196.  
  1197.     $meth;
  1198. }
  1199.  
  1200. # Same as above, but for name-symmetry
  1201. sub get_proc { shift->get_method(@_) }
  1202.  
  1203. ###############################################################################
  1204. #
  1205. #   Sub Name:       server_loop
  1206. #
  1207. #   Description:    Enter a server-loop situation, using the accept() loop of
  1208. #                   HTTP::Daemon if $self has such an object, or falling back
  1209. #                   Net::Server otherwise.
  1210. #
  1211. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1212. #                   $self     in      ref       Object of this class
  1213. #                   %args     in      hash      Additional parameters to set up
  1214. #                                                 before calling the superclass
  1215. #                                                 Run method
  1216. #
  1217. #   Returns:        string if error, otherwise void
  1218. #
  1219. ###############################################################################
  1220. sub server_loop
  1221. {
  1222.     my $self = shift;
  1223.  
  1224.     if ($self->{__daemon})
  1225.     {
  1226.         my ($conn, $req, $resp, $reqxml, $return, $respxml, $exit_now,
  1227.             $timeout);
  1228.  
  1229.         my %args = @_;
  1230.  
  1231.         # Localize and set the signal handler as an exit route
  1232.         my @exit_signals;
  1233.  
  1234.         if (exists $args{signal} and $args{signal} ne 'NONE')
  1235.         {
  1236.             @exit_signals =
  1237.                 (ref $args{signal}) ? @{$args{signal}} : $args{signal};
  1238.         }
  1239.         else
  1240.         {
  1241.             push @exit_signals, 'INT';
  1242.         }
  1243.  
  1244.         local @SIG{@exit_signals} = ( sub { $exit_now++ } ) x @exit_signals;
  1245.  
  1246.         $self->started('set');
  1247.         $exit_now = 0;
  1248.         $timeout = $self->{__daemon}->timeout(1);
  1249.         while (! $exit_now)
  1250.         {
  1251.             $conn = $self->{__daemon}->accept;
  1252.  
  1253.             last if $exit_now;
  1254.             next unless $conn;
  1255.             $conn->timeout($self->timeout);
  1256.             $self->process_request($conn);
  1257.             $conn->close;
  1258.             undef $conn; # Free up any lingering resources
  1259.         }
  1260.  
  1261.         $self->{__daemon}->timeout($timeout) if defined $timeout;
  1262.     }
  1263.     else
  1264.     {
  1265.         # This is the Net::Server block, but for now HTTP::Daemon is needed
  1266.         # for the code that converts socket data to a HTTP::Request object
  1267.         require HTTP::Daemon;
  1268.  
  1269.         my $conf_file_flag = 0;
  1270.         my $port_flag = 0;
  1271.         my $host_flag = 0;
  1272.  
  1273.         for (my $i = 0; $i < @_; $i += 2)
  1274.         {
  1275.             $conf_file_flag = 1 if ($_[$i] eq 'conf_file');
  1276.             $port_flag = 1 if ($_[$i] eq 'port');
  1277.             $host_flag = 1 if ($_[$i] eq 'host');
  1278.         }
  1279.  
  1280.         # An explicitly-given conf-file trumps any specified at creation
  1281.         if (exists($self->{conf_file}) and (! $conf_file_flag))
  1282.         {
  1283.             push (@_, 'conf_file', $self->{conf_file});
  1284.             $conf_file_flag = 1;
  1285.         }
  1286.  
  1287.         # Don't do this next part if they've already given a port, or are
  1288.         # pointing to a config file:
  1289.         unless ($conf_file_flag or $port_flag)
  1290.         {
  1291.             push (@_, 'port', $self->{port} || $self->port || 9000);
  1292.             push (@_, 'host', $self->{host} || $self->host || '*');
  1293.         }
  1294.  
  1295.         # Try to load the Net::Server::MultiType module
  1296.         eval { require Net::Server::MultiType; };
  1297.         return ref($self) .
  1298.             "::server_loop: Error loading Net::Server::MultiType: $@"
  1299.                 if ($@);
  1300.         unshift(@RPC::XML::Server::ISA, 'Net::Server::MultiType');
  1301.  
  1302.         $self->started('set');
  1303.         # ...and we're off!
  1304.         $self->run(@_);
  1305.     }
  1306.  
  1307.     return;
  1308. }
  1309.  
  1310. ###############################################################################
  1311. #
  1312. #   Sub Name:       post_configure_loop
  1313. #
  1314. #   Description:    Called by the Net::Server classes after all the config
  1315. #                   steps have been done and merged.
  1316. #
  1317. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1318. #                   $self     in      ref       Class object
  1319. #
  1320. #   Returns:        $self
  1321. #
  1322. ###############################################################################
  1323. sub post_configure_hook
  1324. {
  1325.     my $self = shift;
  1326.  
  1327.     $self->{__host} = $self->{server}->{host};
  1328.     $self->{__port} = $self->{server}->{port};
  1329.  
  1330.     $self;
  1331. }
  1332.  
  1333. ###############################################################################
  1334. #
  1335. #   Sub Name:       pre_loop_hook
  1336. #
  1337. #   Description:    Called by Net::Server classes after the post_bind method,
  1338. #                   but before the socket-accept loop starts.
  1339. #
  1340. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1341. #                   $self     in      ref       Object instance
  1342. #
  1343. #   Globals:       %ENV
  1344. #
  1345. #   Returns:        $self
  1346. #
  1347. ###############################################################################
  1348. sub pre_loop_hook
  1349. {
  1350.     # We have to disable the __DIE__ handler for the sake of XML::Parser::Expat
  1351.     $SIG{__DIE__} = '';
  1352. }
  1353.  
  1354. ###############################################################################
  1355. #
  1356. #   Sub Name:       process_request
  1357. #
  1358. #   Description:    This is provided for the case when we run as a subclass
  1359. #                   of Net::Server.
  1360. #
  1361. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1362. #                   $self     in      ref       This class object
  1363. #                   $conn     in      ref       If present, it's a connection
  1364. #                                                 object from HTTP::Daemon
  1365. #
  1366. #   Returns:        void
  1367. #
  1368. ###############################################################################
  1369. sub process_request
  1370. {
  1371.     my $self = shift;
  1372.     my $conn = shift;
  1373.  
  1374.     my ($req, $reqxml, $resp, $respxml, $do_compress, $parser, $com_engine,
  1375.         $length, $read, $buf, $resp_fh, $tmpfile,
  1376.         $peeraddr, $peerhost, $peerport);
  1377.  
  1378.     my $me = ref($self) . '::process_request';
  1379.     unless ($conn and ref($conn))
  1380.     {
  1381.         $conn = $self->{server}->{client};
  1382.         bless $conn, 'HTTP::Daemon::ClientConn';
  1383.         ${*$conn}{'httpd_daemon'} = $self;
  1384.  
  1385.         if ($IO::Socket::SSL::VERSION and
  1386.             $RPC::XML::Server::IO_SOCKET_SSL_HACK_NEEDED)
  1387.         {
  1388.             no strict 'vars';
  1389.             unshift @HTTP::Daemon::ClientConn::ISA, 'IO::Socket::SSL';
  1390.             $RPC::XML::Server::IO_SOCKET_SSL_HACK_NEEDED = 0;
  1391.         }
  1392.     }
  1393.  
  1394.     # These will be attached to any and all request objects that are
  1395.     # (successfully) read from $conn.
  1396.     $peeraddr = $conn->peeraddr;
  1397.     $peerport = $conn->peerport;
  1398.     $peerhost = $conn->peerhost;
  1399.     while ($req = $conn->get_request('headers only'))
  1400.     {
  1401.         if ($req->method eq 'HEAD')
  1402.         {
  1403.             # The HEAD method will be answered with our return headers,
  1404.             # both as a means of self-identification and a verification
  1405.             # of live-status. All the headers were pre-set in the cached
  1406.             # HTTP::Response object. Also, we don't count this for stats.
  1407.             $conn->send_response($self->response);
  1408.         }
  1409.         elsif ($req->method eq 'POST')
  1410.         {
  1411.             # Get a XML::Parser::ExpatNB object
  1412.             $parser = $self->parser->parse();
  1413.  
  1414.             if (($req->content_encoding || '') =~ $self->compress_re)
  1415.             {
  1416.                 unless ($self->compress)
  1417.                 {
  1418.                     $conn->send_error(RC_BAD_REQUEST,
  1419.                                       "$me: Compression not permitted in " .
  1420.                                       'requests');
  1421.                     next;
  1422.                 }
  1423.  
  1424.                 $do_compress = 1;
  1425.             }
  1426.  
  1427.             if (($req->content_encoding || '') =~ /chunked/i)
  1428.             {
  1429.                 # Technically speaking, we're not supposed to honor chunked
  1430.                 # transfer-encoding...
  1431.             }
  1432.             else
  1433.             {
  1434.                 $length = $req->content_length;
  1435.                 if ($do_compress)
  1436.                 {
  1437.                     # Spin up the compression engine
  1438.                     unless ($com_engine = Compress::Zlib::inflateInit())
  1439.                     {
  1440.                         $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1441.                                           "$me: Unable to initialize the " .
  1442.                                           'Compress::Zlib engine');
  1443.                         next;
  1444.                     }
  1445.                 }
  1446.  
  1447.                 $buf = '';
  1448.                 while ($length > 0)
  1449.                 {
  1450.                     if ($buf = $conn->read_buffer)
  1451.                     {
  1452.                         # Anything that get_request read, but didn't use, was
  1453.                         # left in the read buffer. The call to sysread() should
  1454.                         # NOT be made until we've emptied this source, first.
  1455.                         $read = length($buf);
  1456.                         $conn->read_buffer(''); # Clear it, now that it's read
  1457.                     }
  1458.                     else
  1459.                     {
  1460.                         $read = sysread($conn, $buf,
  1461.                                         ($length < 2048) ? $length : 2048);
  1462.                         unless ($read)
  1463.                         {
  1464.                             # Convert this print to a logging-hook call.
  1465.                             # Umm, when I have real logging hooks, I mean.
  1466.                             # The point is, odds are very good that $conn is
  1467.                             # dead to us now, and I don't want this package
  1468.                             # taking over SIGPIPE as well as the ones it
  1469.                             # already monopolizes.
  1470.                             #print STDERR "Error: Connection Dropped\n";
  1471.                             return undef;
  1472.                         }
  1473.                     }
  1474.                     $length -= $read;
  1475.                     if ($do_compress)
  1476.                     {
  1477.                         unless ($buf = $com_engine->inflate($buf))
  1478.                         {
  1479.                             $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1480.                                               "$me: Error inflating " .
  1481.                                               'compressed data');
  1482.                             # This error also means that even if Keep-Alive
  1483.                             # is set, we don't know how much of the stream
  1484.                             # is corrupted.
  1485.                             $conn->force_last_request;
  1486.                             next;
  1487.                         }
  1488.                     }
  1489.  
  1490.                     eval { $parser->parse_more($buf); };
  1491.                     if ($@)
  1492.                     {
  1493.                         $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1494.                                           "$me: Parse error in (compressed) " .
  1495.                                           "XML request (mid): $@");
  1496.                         # Again, the stream is likely corrupted
  1497.                         $conn->force_last_request;
  1498.                         next;
  1499.                     }
  1500.                 }
  1501.  
  1502.                 eval { $reqxml = $parser->parse_done(); };
  1503.                 if ($@)
  1504.                 {
  1505.                     $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1506.                                       "$me: Parse error in (compressed) " .
  1507.                                       "XML request (end): $@");
  1508.                     next;
  1509.                 }
  1510.             }
  1511.  
  1512.             # Dispatch will always return a RPC::XML::response.
  1513.             # RT29351: If there was an error from RPC::XML::Parser (such as
  1514.             # a message that didn't conform to spec), then return it directly
  1515.             # as a fault, don't have dispatch() try and handle it.
  1516.             if (ref $reqxml)
  1517.             {
  1518.                 # Set localized keys on $self, based on the connection info
  1519.                 local $self->{peeraddr} = $peeraddr;
  1520.                 local $self->{peerhost} = $peerhost;
  1521.                 local $self->{peerport} = $peerport;
  1522.                 $respxml = $self->dispatch($reqxml);
  1523.             }
  1524.             else
  1525.             {
  1526.                 $respxml = RPC::XML::fault->new(RC_INTERNAL_SERVER_ERROR,
  1527.                                                 $reqxml);
  1528.                 $respxml = RPC::XML::response->new($respxml);
  1529.             }
  1530.  
  1531.             # Clone the pre-fab response and set headers
  1532.             $resp = $self->response->clone;
  1533.             # Should we apply compression to the outgoing response?
  1534.             $do_compress = 0; # In case it was set above for incoming data
  1535.             if ($self->compress and
  1536.                 ($respxml->length > $self->compress_thresh) and
  1537.                 (($req->header('Accept-Encoding') || '') =~
  1538.                  $self->compress_re))
  1539.             {
  1540.                 $do_compress = 1;
  1541.                 $resp->header(Content_Encoding => $self->compress);
  1542.             }
  1543.             # Next step, determine the response disposition. If it is above the
  1544.             # threshhold for a requested file cut-off, send it to a temp file
  1545.             if ($self->message_file_thresh and
  1546.                 $self->message_file_thresh < $respxml->length)
  1547.             {
  1548.                 require File::Spec;
  1549.                 # Start by creating a temp-file
  1550.                 $tmpfile = $self->message_temp_dir || File::Spec->tmpdir;
  1551.                 $tmpfile = File::Spec->catfile($tmpfile,
  1552.                                                __PACKAGE__ . $$ . time);
  1553.                 $tmpfile =~ s/::/-/g;
  1554.                 unless (open($resp_fh, "+> $tmpfile"))
  1555.                 {
  1556.                     $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1557.                                       "$me: Error opening $tmpfile: $!");
  1558.                     next;
  1559.                 }
  1560.                 unlink $tmpfile;
  1561.                 # Make it auto-flush
  1562.                 my $old_fh = select($resp_fh); $| = 1; select($old_fh);
  1563.  
  1564.                 # Now that we have it, spool the response to it. This is a
  1565.                 # little hairy, since we still have to allow for compression.
  1566.                 # And though the response could theoretically be HUGE, in
  1567.                 # order to compress we have to write it to a second temp-file
  1568.                 # first, so that we can compress it into the primary handle.
  1569.                 if ($do_compress)
  1570.                 {
  1571.                     my $fh2;
  1572.                     $tmpfile .= '-2';
  1573.                     unless (open($fh2, "+> $tmpfile"))
  1574.                     {
  1575.                         $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1576.                                           "$me: Error opening $tmpfile: $!");
  1577.                         next;
  1578.                     }
  1579.                     unlink $tmpfile;
  1580.                     # Make it auto-flush
  1581.                     $old_fh = select($fh2); $| = 1; select($old_fh);
  1582.  
  1583.                     # Write the request to the second FH
  1584.                     $respxml->serialize($fh2);
  1585.                     seek($fh2, 0, 0);
  1586.  
  1587.                     # Spin up the compression engine
  1588.                     unless ($com_engine = Compress::Zlib::deflateInit())
  1589.                     {
  1590.                         $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1591.                                           "$me: Unable to initialize the " .
  1592.                                           'Compress::Zlib engine');
  1593.                         next;
  1594.                     }
  1595.  
  1596.                     # Spool from the second FH through the compression engine,
  1597.                     # into the intended FH.
  1598.                     $buf = '';
  1599.                     my $out;
  1600.                     while (read($fh2, $buf, 4096))
  1601.                     {
  1602.                         unless (defined($out = $com_engine->deflate(\$buf)))
  1603.                         {
  1604.                             $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1605.                                               "$me: Compression failure in " .
  1606.                                               'deflate()');
  1607.                             next;
  1608.                         }
  1609.                         print $resp_fh $out;
  1610.                     }
  1611.                     # Make sure we have all that's left
  1612.                     unless (defined($out = $com_engine->flush))
  1613.                     {
  1614.                         $conn->send_error(RC_INTERNAL_SERVER_ERROR,
  1615.                                           "$me: Compression flush failure in" .
  1616.                                           ' deflate()');
  1617.                         next;
  1618.                     }
  1619.                     print $resp_fh $out;
  1620.  
  1621.                     # Close the secondary FH. Rewinding the primary is done
  1622.                     # later.
  1623.                     close($fh2);
  1624.                 }
  1625.                 else
  1626.                 {
  1627.                     $respxml->serialize($resp_fh);
  1628.                 }
  1629.                 seek($resp_fh, 0, 0);
  1630.  
  1631.                 $resp->content_length(-s $resp_fh);
  1632.                 $resp->content(sub {
  1633.                                    my $b = '';
  1634.                                    return undef unless
  1635.                                        defined(read($resp_fh, $b, 4096));
  1636.                                    $b;
  1637.                                });
  1638.             }
  1639.             else
  1640.             {
  1641.                 # Treat the content strictly in-memory
  1642.                 $buf = $respxml->as_string;
  1643.                 $buf = Compress::Zlib::compress($buf) if $do_compress;
  1644.                 $resp->content($buf);
  1645.                 $resp->content_length($respxml->length);
  1646.             }
  1647.  
  1648.             $conn->send_response($resp);
  1649.             undef $resp;
  1650.         }
  1651.         else
  1652.         {
  1653.             $conn->send_error(RC_FORBIDDEN);
  1654.         }
  1655.     }
  1656.  
  1657.     return;
  1658. }
  1659.  
  1660. ###############################################################################
  1661. #
  1662. #   Sub Name:       dispatch
  1663. #
  1664. #   Description:    Route the request by parsing it, determining what the
  1665. #                   Perl routine should be, etc.
  1666. #
  1667. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1668. #                   $self     in      ref       Object of this class
  1669. #                   $xml      in      ref       Reference to the XML text, or
  1670. #                                                 a RPC::XML::request object.
  1671. #                                                 If it is a listref, assume
  1672. #                                                 [ name, @args ].
  1673. #                   $reftable in      hashref   If present, a reference to the
  1674. #                                                 current-running table of
  1675. #                                                 back-references
  1676. #
  1677. #   Returns:        RPC::XML::response object
  1678. #
  1679. ###############################################################################
  1680. sub dispatch
  1681. {
  1682.     my ($self, $xml) = @_;
  1683.  
  1684.     my ($reqobj, @data, $response, $name, $meth);
  1685.  
  1686.     if (ref($xml) eq 'SCALAR')
  1687.     {
  1688.         $reqobj = $self->parser->parse($$xml);
  1689.         return RPC::XML::response
  1690.             ->new(RPC::XML::fault->new(200, "XML parse failure: $reqobj"))
  1691.                 unless (ref $reqobj);
  1692.     }
  1693.     elsif (ref($xml) eq 'ARRAY')
  1694.     {
  1695.         # This is sort of a cheat, to make the system.multicall API call a
  1696.         # lot easier. The syntax isn't documented in the manual page, for good
  1697.         # reason.
  1698.         $reqobj = RPC::XML::request->new(shift(@$xml), @$xml);
  1699.     }
  1700.     elsif (ref($xml) and $xml->isa('RPC::XML::request'))
  1701.     {
  1702.         $reqobj = $xml;
  1703.     }
  1704.     else
  1705.     {
  1706.         $reqobj = $self->parser->parse($xml);
  1707.         return RPC::XML::response
  1708.             ->new(RPC::XML::fault->new(200, "XML parse failure: $reqobj"))
  1709.                 unless (ref $reqobj);
  1710.     }
  1711.  
  1712.     @data = @{$reqobj->args};
  1713.     $name = $reqobj->name;
  1714.  
  1715.     # Get the method, call it, and bump the internal requests counter. Create
  1716.     # a fault object if there is problem with the method object itself.
  1717.     if (ref($meth = $self->get_method($name)))
  1718.     {
  1719.         $response = $meth->call($self, @data);
  1720.         $self->{__requests}++
  1721.             unless (($name eq 'system.status') && @data &&
  1722.                     ($data[0]->type eq 'boolean') && ($data[0]->value));
  1723.     }
  1724.     else
  1725.     {
  1726.         $response = RPC::XML::fault->new(300, $meth);
  1727.     }
  1728.  
  1729.     # All the eval'ing and error-trapping happened within the method class
  1730.     RPC::XML::response->new($response);
  1731. }
  1732.  
  1733. ###############################################################################
  1734. #
  1735. #   Sub Name:       call
  1736. #
  1737. #   Description:    This is an internal, end-run-around-dispatch() method to
  1738. #                   allow the RPC methods that this server has and knows about
  1739. #                   to call each other through their reference to the server
  1740. #                   object.
  1741. #
  1742. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1743. #                   $self     in      ref       Object of this class
  1744. #                   $name     in      scalar    Name of the method to call
  1745. #                   @args     in      list      Arguments (if any) to pass
  1746. #
  1747. #   Returns:        Success:    return value of the call
  1748. #                   Failure:    error string
  1749. #
  1750. ###############################################################################
  1751. sub call
  1752. {
  1753.     my ($self, $name, @args) = @_;
  1754.  
  1755.     my $meth;
  1756.  
  1757.     #
  1758.     # Two VERY important notes here: The values in @args are not pre-treated
  1759.     # in any way, so not only should the receiver understand what they're
  1760.     # getting, there's no signature checking taking place, either.
  1761.     #
  1762.     # Second, if the normal return value is not distinguishable from a string,
  1763.     # then the caller may not recognize if an error occurs.
  1764.     #
  1765.  
  1766.     return $meth unless ref($meth = $self->get_method($name));
  1767.     $meth->call($self, @args);
  1768. }
  1769.  
  1770. ###############################################################################
  1771. #
  1772. #   Sub Name:       add_default_methods
  1773. #
  1774. #   Description:    This adds all the methods that were shipped with this
  1775. #                   package, by threading through to add_methods_in_dir()
  1776. #                   with the global constant $INSTALL_DIR.
  1777. #
  1778. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1779. #                   $self     in      ref       Object reference/static class
  1780. #                   @details  in      ref       Details of names to add or skip
  1781. #
  1782. #   Globals:        $INSTALL_DIR
  1783. #
  1784. #   Returns:        $self
  1785. #
  1786. ###############################################################################
  1787. sub add_default_methods
  1788. {
  1789.     shift->add_methods_in_dir($INSTALL_DIR, @_);
  1790. }
  1791.  
  1792. ###############################################################################
  1793. #
  1794. #   Sub Name:       add_methods_in_dir
  1795. #
  1796. #   Description:    This adds all methods specified in the directory passed,
  1797. #                   in accordance with the details specified.
  1798. #
  1799. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1800. #                   $self     in      ref       Class instance
  1801. #                   $dir      in      scalar    Directory to scan
  1802. #                   @details  in      list      Possible hanky-panky with the
  1803. #                                                 list of methods to install
  1804. #
  1805. #   Returns:        $self
  1806. #
  1807. ###############################################################################
  1808. sub add_methods_in_dir
  1809. {
  1810.     my $self = shift;
  1811.     my $dir = shift;
  1812.     my @details = @_;
  1813.  
  1814.     my $negate = 0;
  1815.     my $detail = 0;
  1816.     my (%details, $ret);
  1817.  
  1818.     if (@details)
  1819.     {
  1820.         $detail = 1;
  1821.         if ($details[0] =~ /^-?except/i)
  1822.         {
  1823.             $negate = 1;
  1824.             shift(@details);
  1825.         }
  1826.         for (@details) { $_ .= '.xpl' unless /\.xpl$/ }
  1827.         @details{@details} = (1) x @details;
  1828.     }
  1829.  
  1830.     local(*D);
  1831.     opendir(D, $dir) || return "Error opening $dir for reading: $!";
  1832.     my @files = grep($_ =~ /\.xpl$/, readdir(D));
  1833.     closedir D;
  1834.  
  1835.     for (@files)
  1836.     {
  1837.         # Use $detail as a short-circuit to avoid the other tests when we can
  1838.         next if ($detail and
  1839.                  $negate ? $details{$_} : ! $details{$_});
  1840.         # n.b.: Giving the full path keeps add_method from having to search
  1841.         $ret = $self->add_method(File::Spec->catfile($dir, $_));
  1842.         return $ret unless ref $ret;
  1843.     }
  1844.  
  1845.     $self;
  1846. }
  1847.  
  1848. # Same as above, but for name-symmetry
  1849. sub add_procs_in_dir { shift->add_methods_in_dir(@_) }
  1850.  
  1851. ###############################################################################
  1852. #
  1853. #   Sub Name:       delete_method
  1854. #
  1855. #   Description:    Remove any current binding for the named method on the
  1856. #                   calling server object. Note that if this method is shared
  1857. #                   across other server objects, it won't be destroyed until
  1858. #                   the last server deletes it.
  1859. #
  1860. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1861. #                   $self     in      ref       Object of this class
  1862. #                   $name     in      scalar    Name of method to lost
  1863. #
  1864. #   Returns:        Success:    $self
  1865. #                   Failure:    error message
  1866. #
  1867. ###############################################################################
  1868. sub delete_method
  1869. {
  1870.     my $self = shift;
  1871.     my $name = shift;
  1872.  
  1873.     if ($name)
  1874.     {
  1875.         if ($self->{__method_table}->{$name})
  1876.         {
  1877.             delete $self->{__method_table}->{$name};
  1878.             return $self;
  1879.         }
  1880.     }
  1881.     else
  1882.     {
  1883.         return ref($self) . "::delete_method: No such method $name";
  1884.     }
  1885. }
  1886.  
  1887. # Same as above, but for name-symmetry
  1888. sub delete_proc { shift->delete_method(@_) }
  1889.  
  1890. ###############################################################################
  1891. #
  1892. #   Sub Name:       list_methods
  1893. #
  1894. #   Description:    Return a list of the methods this object has published.
  1895. #                   Returns the names, not the objects.
  1896. #
  1897. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1898. #                   $self     in      ref       Object of this class
  1899. #
  1900. #   Returns:        List of names, possibly empty
  1901. #
  1902. ###############################################################################
  1903. sub list_methods
  1904. {
  1905.     keys %{$_[0]->{__method_table}};
  1906. }
  1907.  
  1908. # Same as above, but for name-symmetry
  1909. sub list_procs { shift->list_methods(@_) }
  1910.  
  1911. ###############################################################################
  1912. #
  1913. #   Sub Name:       share_methods
  1914. #
  1915. #   Description:    Share the named methods as found on $src_srv into the
  1916. #                   method table of the calling object.
  1917. #
  1918. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1919. #                   $self     in      ref       Object of this class
  1920. #                   $src_srv  in      ref       Another object of this class
  1921. #                   @names    in      list      One or more method names
  1922. #
  1923. #   Returns:        Success:    $self
  1924. #                   Failure:    error message
  1925. #
  1926. ###############################################################################
  1927. sub share_methods
  1928. {
  1929.     my $self    = shift;
  1930.     my $src_srv = shift;
  1931.     my @names   = @_;
  1932.  
  1933.     my ($me, $pkg, %tmp, @tmp, $tmp, $meth, @list, @missing);
  1934.  
  1935.     $me = ref($self) . '::share_methods';
  1936.     $pkg = __PACKAGE__; # So it can go inside quoted strings
  1937.  
  1938.     return "$me: First arg not derived from $pkg, cannot share"
  1939.         unless ((ref $src_srv) && (UNIVERSAL::isa($src_srv, $pkg)));
  1940.     return "$me: Must specify at least one method name for sharing"
  1941.         unless @names;
  1942.  
  1943.     #
  1944.     # Scan @names for any regez objects, and if found insert the matches into
  1945.     # the list.
  1946.     #
  1947.     # Only do this once:
  1948.     #
  1949.     @tmp = keys %{$src_srv->{__method_table}};
  1950.     for $tmp (@names)
  1951.     {
  1952.         if (ref($names[$tmp]) eq 'Regexp')
  1953.         {
  1954.             $tmp{$_}++ for (grep($_ =~ $tmp, @tmp));
  1955.         }
  1956.         else
  1957.         {
  1958.             $tmp{$tmp}++;
  1959.         }
  1960.     }
  1961.     # This has the benefit of trimming any redundancies caused by regex's
  1962.     @names = keys %tmp;
  1963.  
  1964.     #
  1965.     # Note that the method refs are saved until we've verified all of them.
  1966.     # If we have to return a failure message, I don't want to leave a half-
  1967.     # finished job or have to go back and undo (n-1) additions because of one
  1968.     # failure.
  1969.     #
  1970.     for (@names)
  1971.     {
  1972.         $meth = $src_srv->get_method($_);
  1973.         if (ref $meth)
  1974.         {
  1975.             push(@list, $meth);
  1976.         }
  1977.         else
  1978.         {
  1979.             push(@missing, $_);
  1980.         }
  1981.     }
  1982.  
  1983.     if (@missing)
  1984.     {
  1985.         return "$me: One or more methods not found on source object: @missing";
  1986.     }
  1987.     else
  1988.     {
  1989.         $self->add_method($_) for (@list);
  1990.     }
  1991.  
  1992.     $self;
  1993. }
  1994.  
  1995. # Same as above, but for name-symmetry
  1996. sub share_procs { shift->share_methods(@_) }
  1997.  
  1998. ###############################################################################
  1999. #
  2000. #   Sub Name:       copy_methods
  2001. #
  2002. #   Description:    Copy the named methods as found on $src_srv into the
  2003. #                   method table of the calling object. This differs from
  2004. #                   share() above in that only the coderef is shared, the
  2005. #                   rest of the method is a completely new object.
  2006. #
  2007. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  2008. #                   $self     in      ref       Object of this class
  2009. #                   $src_srv  in      ref       Another object of this class
  2010. #                   @names    in      list      One or more method names
  2011. #
  2012. #   Returns:        Success:    $self
  2013. #                   Failure:    error message
  2014. #
  2015. ###############################################################################
  2016. sub copy_methods
  2017. {
  2018.     my $self    = shift;
  2019.     my $src_srv = shift;
  2020.     my @names   = shift;
  2021.  
  2022.     my ($me, $pkg, %tmp, @tmp, $tmp, $meth, @list, @missing);
  2023.  
  2024.     $me = ref($self) . '::copy_methods';
  2025.     $pkg = __PACKAGE__; # So it can go inside quoted strings
  2026.  
  2027.     return "$me: First arg not derived from $pkg, cannot copy"
  2028.         unless ((ref $src_srv) && (UNIVERSAL::isa($src_srv, $pkg)));
  2029.     return "$me: Must specify at least one method name/regex for copying"
  2030.         unless @names;
  2031.  
  2032.     #
  2033.     # Scan @names for any regez objects, and if found insert the matches into
  2034.     # the list.
  2035.     #
  2036.     # Only do this once:
  2037.     #
  2038.     @tmp = keys %{$src_srv->{__method_table}};
  2039.     for $tmp (@names)
  2040.     {
  2041.         if (ref($names[$tmp]) eq 'Regexp')
  2042.         {
  2043.             $tmp{$_}++ for (grep($_ =~ $tmp, @tmp));
  2044.         }
  2045.         else
  2046.         {
  2047.             $tmp{$tmp}++;
  2048.         }
  2049.     }
  2050.     # This has the benefit of trimming any redundancies caused by regex's
  2051.     @names = keys %tmp;
  2052.  
  2053.     #
  2054.     # Note that the method clones are saved until we've verified all of them.
  2055.     # If we have to return a failure message, I don't want to leave a half-
  2056.     # finished job or have to go back and undo (n-1) additions because of one
  2057.     # failure.
  2058.     #
  2059.     for (@names)
  2060.     {
  2061.         $meth = $src_srv->get_method($_);
  2062.         if (ref $meth)
  2063.         {
  2064.             push(@list, $meth->clone);
  2065.         }
  2066.         else
  2067.         {
  2068.             push(@missing, $_);
  2069.         }
  2070.     }
  2071.  
  2072.     if (@missing)
  2073.     {
  2074.         return "$me: One or more methods not found on source object: @missing";
  2075.     }
  2076.     else
  2077.     {
  2078.         $self->add_method($_) for (@list);
  2079.     }
  2080.  
  2081.     $self;
  2082. }
  2083.  
  2084. # Same as above, but for name-symmetry
  2085. sub copy_procs { shift->copy_methods(@_) }
  2086.  
  2087. ###############################################################################
  2088. #
  2089. #   Sub Name:       timeout
  2090. #
  2091. #   Description:    This sets the timeout for processing connections after
  2092. #                   a new connection has been accepted.  It returns the old
  2093. #                   timeout value.  If you pass in no value, it returns
  2094. #                   the current timeout.
  2095. #
  2096. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  2097. #                   $self     in      ref       Object reference/static class
  2098. #                   $timeout  in      ref       New timeout value
  2099. #
  2100. #   Returns:        $self->{__timeout}
  2101. #
  2102. ###############################################################################
  2103. sub timeout
  2104. {
  2105.     my $self    = shift;
  2106.     my $timeout = shift;
  2107.  
  2108.     my $old_timeout = $self->{__timeout};
  2109.     if ($timeout)
  2110.     {
  2111.         $self->{__timeout} = $timeout;
  2112.     }
  2113.     return $old_timeout;
  2114. }
  2115.